import zmail
import pymysql
from qiniu import Auth, put_file, etag
import datetime
import re
import predict
import time

# from timeloop import Timeloop

# 七牛云 AK: uf0yhkrLlaMLUiQMlcvBkYVNQUk8bLD3hOknOJIz
#       SK: gzicN5KrUfawj0iJyHJZS0ixzsy6Dpfq_DV6nZBW

conn = pymysql.connect(
    host="42.192.94.142",  # ip地址
    port=3306,  # 端口号
    db="pb_cms_base",  # 数据库名 bonfire_email
    user='group7',
    password="ctgu123456",
    charset="utf8"  # 编码格式
)

# 七牛云配置
q = Auth('uf0yhkrLlaMLUiQMlcvBkYVNQUk8bLD3hOknOJIz', 'gzicN5KrUfawj0iJyHJZS0ixzsy6Dpfq_DV6nZBW')
# 上传空间
bucket_name = 'bonfire-email'


def save_and_judge(temp_id, email_content):
    f = open('../data/emails/' + str(temp_id), 'w', encoding='utf-8')
    for line in email_content:
        f.write(line)
    f.close()
    return predict.read_one_file_to_predict('../data/emails', str(temp_id))
    # return predict.read_one_file_to_predict('../data/emails', str(temp_id))


# def intervalFunc():
while True:
    cursor = conn.cursor()
    select_sql = "select * from e_mailbox where code is not NULL"
    row = cursor.execute(select_sql)
    mailboxs = cursor.fetchall()

    for mailbox in mailboxs:
        server_email = mailbox[0]

        # if server_email == "ctgu_email@163.com":    # 记得24小时后关掉这段代码
        #     continue

        server = zmail.server(server_email, mailbox[2])
        # server = zmail.server('zhilhe@163.com', 'YIAXOWNGMSJHEDNH')
        # 获取当前时间和前5s时间
        t1 = datetime.datetime.now() + datetime.timedelta(minutes=-30/60)
        convertTime = t1.strftime("%Y-%m-%d %H:%M:%S")
        mails = server.get_mails(start_time=convertTime)  # start_time = convertTime
        # 遍历邮件
        email_temp_id = 0  # 临时保存到文件中的id，不需要保存到数据库中
        for mail in mails:

            # 保存附件
            print("收到来自：", mail['subject'], " 的邮件")
            fileName = zmail.save_attachment(mail, target_path="file/", overwrite=True)
            # 生成上传 Token，可以指定过期时间等
            token = q.upload_token(bucket_name, fileName, 3600)
            # 上传文件到七牛云
            if fileName is not None:
                filePath = './file/' + fileName
                info = put_file(token, fileName, filePath, version='v2')
                path = 'http://rewgjkhsm.hn-bkt.clouddn.com/' + fileName
            else:
                path = None

            if mail['content_html'] is not None:
                content = mail['content_html']
            elif mail['content_text'] is not None:
                content = mail['content_text'][0]
            else:
                content = None

            if len(mail['content_text']) == 0:
                text = mail['subject']
            else:
                text = mail['content_text']
            text = re.sub(r'\\n+', '', str(text))
            text = re.sub(r'\\u3000+', '', text)
            text = re.sub(r'\\r+', '', text)
            text = re.sub(r'&nbsp;+', '', text)
            text = re.sub(r'\[\'+', '', text)
            text = re.sub(r'\'\]+', '', text)

            # print(text)
            result = save_and_judge(email_temp_id, content)
            mail['mark'] = result
            print("判断Title：", mail['subject'], " 是否垃圾邮件：", result)
            email_temp_id += 1
            sql = "insert into e_email (address, post_address, title, content, text, create_time, status, mark, file) value (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
            row = cursor.execute(sql, [server_email, mail['from'], mail['subject'], content, text, mail['date'], 0,
                                       mail['mark'], path])

    conn.commit()
    print("等待10秒后继续处理")
    time.sleep(20)

conn.close()
